# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import socket
import sys
import datetime
import time
from concurrent.futures import ThreadPoolExecutor

from absl import flags

from coin.exchange.bittrex_v1.kr_rest.feed_client import BittrexV1Feed
from coin.exchange.util.simple_record import RecordWriter

FLAGS = flags.FLAGS

flags.DEFINE_bool('verbose', False, 'verbose')


def main_run(feed, writer):
  try:
    feed.query_book()
    pb = feed.get_proto_feed_float()
    writer.write_record(pb.SerializeToString())
    writer.flush()
    if FLAGS.verbose:
      print(pb)
  except Exception as e:
    print("exception", e)


def main(argv):
  argv = FLAGS(argv)
  POPULAR_SYMBOLS = [
      'BTC-USDT',
      'XRP-BTC',
      'ETH-BTC',
      'XRP-USDT',
      'NEO-BTC',
      'ETH-USDT',
      'BCC-BTC',
      'NEO-USDT',
      'LTC-BTC',
      'ETC-BTC'
  ]
  feeds = [BittrexV1Feed(symbol) for symbol in POPULAR_SYMBOLS]
  files = [
      "data/%s.%s.%s.%s" %
      ('Bittrex', feed.product, socket.gethostname(), datetime.datetime.now().isoformat())
      for feed in feeds
  ]
  for filepath in files:
    print("saving to " + filepath)

  writers = [RecordWriter(filepath) for filepath in files]
  executor = ThreadPoolExecutor(max_workers=len(POPULAR_SYMBOLS))
  while True:
    for result in executor.map(main_run, feeds, writers):
      pass
    time.sleep(1)


if __name__ == "__main__":
  main(sys.argv)
